<?php

/**
 * Plugin zajistuje autentifikaci uzivatele a presmerovani
 *
 */
class Application_Plugin_FmAuth extends Zend_Controller_Plugin_Abstract
{

    /**
     *
     * @var array
     */
    private $_options;

    /**
     * Metoda vrati konkretni hodnotu z konfigurace
     * Pokud klic neni nalezen, vyhodime vyjimku
     *
     * @param string $key
     * @return mixed
     */
    private function _getParam($key)
    {
        if (is_null($this->_options))
        {
            $this->_options = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getApplication()->getOptions();
        }

        if (!array_key_exists($key, $this->_options['lastfm']))
        {
            throw new Zend_Controller_Exception("Param {lastfm.$key} not found in application.ini");
        }
        else
        {
            return $this->_options['lastfm'][$key];
        }
    }

    /**
     * Wrapper nad metodou _getParam
     * Umozni nam pristupovat ke konfiguraci primo pres $this
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->_getParam($key);
    }

    /**
     * Enter description here...
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        // ziskame instanci redirector helperu, ktery ma starosti presmerovani
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');

        if ($request->getActionName() == 'logout')
        {
            return;
        }

        $auth = Zend_Auth::getInstance();


        // token predany z last.fm po autorizaci
        $token = $request->getQuery("token");



        $me = null;

        if ($token)
        {
            try
            {

                $lastfm_data = LastFM::getInstance()->getSession($token);

                $key = (string)$lastfm_data->session->key;
                $name = (string)$lastfm_data->session->name;

                $session = new Zend_Session_Namespace('fm');
                $session->fm = $name;


                $users = new Users();

                $user = $users->findByLastFm($name)->current();

                if (empty($user))
                {
                    $user = $users->createRow();
                }

                //$user->first_name = $facebook_data['first_name'];
                //$user->last_name = $facebook_data['last_name'];
                //$user->email = $facebook_data['email'];
                //$user->locale = $facebook_data['locale'];
                //$user->facebook_id = $uid;
                $user->last_fm_username = $name;
                $user->session_key = $key;
                $user->save();

            }
            catch (Exception $e)
            {
                error_log($e);
            }

            if ($name)
            {

                $adapter = new My_Auth_Adapter_LastFm($name, $key);

                $result = $auth->authenticate($adapter);


                $users = new Users();
                $r = $users->findByLastFm($name);

                if (!empty($r))
                {
                    $user = $r->current();

                    $db = Zend_Db_Table::getDefaultAdapter();


                  $db->update('user', array(
                  'lognum' => new Zend_Db_Expr('lognum + 1'),
                  'ip' => $request->getClientIp(),
                  'last_login' => new Zend_Db_Expr('NOW()'),
                  'browser' => $request->getServer('HTTP_USER_AGENT')),
                  "last_fm_username = '$name'");


                    if (empty($user->last_fm_username) && $request->getActionName() != 'account')
                    {
                        $redirector->gotoRoute(array('controller' => 'user', 'action' => 'account'));
                    }
                }

                if ($request->getQuery('token'))
                {
                    $redirector->gotoRoute(array('controller' => 'index', 'action' => 'index'), 'default', true);
                }
            }
        }




    }

}